package indi.mozping.aio.client;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * @author by mozping
 * @Classname AioClientWriteHandler
 * @Description TODO
 * @Date 2019/4/23 10:10
 */
public class AioClientWriteHandler implements CompletionHandler<Integer, ByteBuffer> {

    private AsynchronousSocketChannel socketChannel;
    private CountDownLatch countDownLatch;

    public AioClientWriteHandler(AsynchronousSocketChannel socketChannel, CountDownLatch countDownLatch) {
        this.socketChannel = socketChannel;
        this.countDownLatch = countDownLatch;
    }

    //写完数据之后被调用
    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        //有可能无法一次性将数据写完,需要检查缓冲区中是否还有数据需要继续进行网络写
        if (buffer.hasRemaining()) {
            socketChannel.write(buffer, buffer, this);
        } else {
            //写操作已经完成，为服务服务端传回来的数据建立缓冲区
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            socketChannel.read(readBuffer, readBuffer, new AioClientReadHandler(socketChannel, countDownLatch));
        }

    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        System.err.println("数据发送失败...");
        try {
            socketChannel.close();
            countDownLatch.countDown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
